<template>
  <div v-loading="detailInfoShow">
    <div class="requestAdd">
      <!-- 筛选按钮 -->
      <div class="search-button" v-if="!contactAddShow">
        <el-button
          v-if="pageType === 'check' && route.name === 'PropertyCheck'"
          class="btn save"
          @click="handleCheckBtn2(projectFormRef, 3, '同意')"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >同意</el-button
        >
        <el-button
          v-if="pageType === 'check' && route.name === 'PropertyCheck'"
          class="btn withdraw"
          @click="handleCheckBtn2(projectFormRef, 4, '拒绝')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >拒绝</el-button
        >

        <el-button
          v-if="pageType === 'check' && route.name === 'PropertyCheck'"
          class="btn withdraw"
          @click="handleCheckBtn2(projectFormRef, 6, '驳回')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >驳回</el-button
        >
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn submit"
          @click="handleAddSave(requestFormRef, 1)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >{{ "提交" }}</el-button
        >
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn save"
          @click="handleAddSave(requestFormRef, 0)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >存为草稿</el-button
        >
        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>
      <el-collapse v-model="activeNames">
        <el-form
          :model="requestForm"
          ref="requestFormRef"
          :rules="queryRules"
          label-width="120px"
          v-enterToNext
          :disabled="pageType === 'detail' || pageType === 'check'"
        >
          <!-- 基础信息 -->
          <el-collapse-item
            name="1"
            v-if="!contactAddShow"
            class="transform-down"
          >
            <template #title>
              <span class="circle"></span>
              <span class="collapse-title"
                >{{
                  pageType !== "detail" && pageType !== "check "
                    ? pageType === "add"
                      ? "新增"
                      : "编辑"
                    : ""
                }}申请信息</span
              >
            </template>
            <div class="request-info">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="申请编号：">
                    <el-input
                      disabled
                      v-model="requestForm.intellectualPropertyCode"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请日期：" prop="applicationTime">
                    <el-date-picker
                      v-model="requestForm.applicationTime"
                      format="YYYY/MM/DD HH:mm:ss"
                      style="width: 100%"
                      class="search-input"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetime"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item
                    label="经办人："
                    prop="userId"
                 
                  >
                    <el-select
                      v-model="requestForm.userId"
                      placeholder="请选择"
                      clearable
                      filterable
                      class="search-input"
                      @change="handleUserChange"
                      value-key="userId"
                      placement="bottom-end"
                    >
                      <el-option disabled :value="null">
                        <div class="auto-top">
                          <span class="auto-item">人员姓名</span>
                          <span class="auto-item">联系方式</span>
                          <span class="auto-item">职位</span>
                          <span class="auto-item">部门</span>
                        </div>
                      </el-option>
                      <el-option
                        v-for="dict in userList"
                        :key="dict.userId"
                        :value="dict.userId"
                        :label="dict.nickName"
                      >
                        <div style="display: flex">
                          <div class="auto-item" :title="dict.nickName">
                            {{ dict.nickName }}
                          </div>
                          <div class="auto-item" :title="dict.phonenumber">
                            {{ dict.phonenumber ? dict.phonenumber : "--" }}
                          </div>
                          <div class="auto-item" :title="dict.postName">
                            {{ dict.postName ? dict.postName : "--" }}
                          </div>
                          <div class="auto-item" :title="dict.fullDeptName">
                            {{ dict.fullDeptName ? dict.fullDeptName : "--" }}
                          </div>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="经办部门：">
                    <el-input
                      disabled
                      v-model="requestForm.deptName"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请类型：" prop="applicationTypes">
                    <el-select
                      v-model="requestForm.applicationTypes"
                      placeholder="请选择"
                      clearable
                      multiple
                      style="width: 100%; height: 100%"
                    >
                      <el-option
                        v-for="dict in applicationList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="预申请名称：" prop="preApplicationName">
                    <el-input
                      v-model="requestForm.preApplicationName"
                      placeholder="请输入"
                      clearable
                      maxlength="20"
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请单位：" prop="applicantUnit">
                    <el-input
                      v-model="requestForm.applicantUnit"
                      placeholder="请输入"
                      clearable
                      maxlength="20"
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="内容描述：" prop="details">
                    <el-input
                      style="width: 100%"
                      v-model="requestForm.details"
                      type="textarea"
                      maxlength="2000"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="备注：">
                    <el-input
                      style="width: 100%"
                      v-model="requestForm.remark"
                      type="textarea"
                      maxlength="2000"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="附件：" prop="suppFileInfoVos">
                    <Upload
                      :fileList="requestForm.suppFileInfoVos"
                      :isFull="true"
                      :limit="10"
                      limitation="property"
                      :showButton="true"
                      @success="(result) => uploadSuccess(result)"
                      @deleteFile="(result) => uploadRemove(result)"
                      :isCanDelete="
                        pageType == 'detail' || pageType == 'check'
                          ? false
                          : true
                      "
                      :disabled="pageType == 'detail' || pageType == 'check'"
                    />
                    <!-- accept=".jpg,.png" -->
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
        </el-form>
      </el-collapse>
    </div>

    <el-dialog
      :title="title"
      v-model="auditDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="审核备注：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="auditRemark"
          placeholder=""
          type="textarea"
          maxlength="2000"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            v-if="auditResult == 3"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >同意</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 4"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >拒绝</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 6"
            @click="saveCheck()"
            v-loading="loadingCheck"
          >
            驳回</el-button
          >
          <el-button style="background-color: #fff" @click="closeAudit()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// import { Picture as IconPicture } from "@element-plus/icons-vue";
import useUserStore from "@/store/modules/user";
import Upload from "@/components/Upload/index";
import { getUserListApi } from "@/api/information/customer";

import { checkPaymentApi, getEndFlag } from "@/api/purchase/payment";
import {
  addPropertyApi,
  getPropertyDetailApi,
  editPropertytApi,
  checkPropertyApi,
} from "@/api/serve/property";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
const route = useRoute();
const emit = defineEmits([
  // 客户新增组件显隐
  "requestAddShow",
  // 更新客户新增组件显隐
  "update:requestAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
//当前用户信息
const userStore = useUserStore();
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
  // 合同用印id
  contractId: {
    type: Number,
    default: null,
  },
  // 合同用印编号
  contractCode: {
    type: Number,
    default: null,
  },
});

// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const requestFormRef = ref();
// 新增联系人表单显隐
const contactAddShow = ref(false);
const loadingCheck = ref(false);

// 选择审核
const auditDialogShow = ref(false);

// 详情加载效果
const detailInfoShow = ref(false);

// 申请类型列表
const applicationList = ref([]);

// 客户表单数据模板
const requestFormTemplate = {
  intellectualPropertyCode: "", //申请编号
  userId: null, // 经办人id
  applicationTime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"), // 申请日期
  details: "", // 	内容描述
  applicationTypes: [], // 申请类型
  preApplicationName: "", // 	预申请名称
  applicantUnit:"", // 申请单位
  deptName: "", // 申请部门
  remark: "", //备注
  suppFileInfoVos: [], // 知识产权附件
  type: 0, // 	按钮类型0：存为草稿；1；提交
};
const data = reactive({
  // 客户表单
  requestForm: JSON.parse(JSON.stringify(requestFormTemplate)),
  // 客户表单校验规则
  queryRules: {
    applicationTime: [
      { required: true, message: "请选择申请日期", trigger: "change" },
    ],
    userId: [{ required: true, message: "请选择经办人", trigger: "change" }],
    applicationTypes: [
      { required: true, message: "请选择申请类型", trigger: "change" },
    ],
    details: [{ required: true, message: "请输入内容描述", trigger: "blur" }],
    preApplicationName: [
      { required: true, message: "请输入预申请名称", trigger: "blur" },
    ],
    applicantUnit: [
      { required: true, message: "请输入申请单位", trigger: "blur" },
    ],
    suppFileInfoVos: [
      { required: true, message: "请上传附件", trigger: "change" },
    ],
  },

  // 用户列表
  userList: [],
  auditRemark: "", //审核备注
  auditResult: null, //审核类型
  applyId: null, //当前数据id
  endFlag: 0,
});

const {
  requestForm,
  queryRules,
  userList,
  auditRemark,
  auditResult,
  applyId,
  endFlag,
} = toRefs(data);

const handleCheckBtn2 = (requestFormRef, type, title) => {
  auditRemark.value = "";
  if (type == 3) {
    auditRemark.value = "同意";
  }

  auditResult.value = type;
  (applyId.value = requestForm.value.intellectualPropertyId),
    (auditDialogShow.value = true);
  loadingCheck.value = false;
};

const saveCheck = async () => {
  if (auditRemark.value === null || auditRemark.value === "") {
    ElMessage.error("审核备注不能为空");
    return;
  }
  try {
    loadingCheck.value = true;
    requestForm.value.paymentCheckStatus = auditResult.value;
    requestForm.value.auditRemark = auditRemark.value;
    let params = {
      auditRemark: auditRemark.value,
      intellectualPropertyId: requestForm.value.intellectualPropertyId,
      propertyCheckStatus: auditResult.value,
    };
    const res = await checkPropertyApi(params);
    auditDialogShow.value = false;
    if (res.code === 200) {
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
      return;
    }
    loadingCheck.value = false;
    emit("update:requestAddShow", false);
    emit("refreshList", false);
  } catch (error) {
    loadingCheck.value = false;
  }
  ElMessage.error(error);
};

const closeAudit = () => {
  auditRemark.value = "";
  auditResult.value = null;
  applyId.value = null;
  auditDialogShow.value = false;
};

/**
 * @description: 保存
 * @param {Object} requestFormRef 客户表单引用
 */
const handleAddSave = async (requestFormRef, type) => {
  if (!requestFormRef) return;
  await requestFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        "确定" + (type == 0 ? "存为草稿" : "提交") + "吗？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          confirmButtonClass: "confirmBtnClass",
          cancelButtonClass: "cancelBtnClass",
        }
      )
        .then(async () => {
          requestForm.value.type = type;
          let res;
          if (!requestForm.value.intellectualPropertyId) {
            // 新增客户
            res = await addPropertyApi(requestForm.value);
          } else {
            // 编辑客户
            res = await editPropertytApi(requestForm.value);
          }
          if (res.code === 200) {
            emit("update:requestAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail" || props.pageType === "check") {
    emit("updateFollowAddShow", false);
    emit("update:requestAddShow", false);
    requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:requestAddShow", false);
        requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理人员选择
 * @param {Number} value 选择值
 */
const handleUserChange = (value) => {
  if (value) {
    const selectUser = userList.value.find((item) => item.userId === value);
    if (selectUser) {
      requestForm.value.deptName = selectUser.deptName;
    }
  } else {
    requestForm.value.deptName = "";
  }
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  requestForm.value.suppFileInfoVos.push({ ...response, businessType: 28 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  requestForm.value.suppFileInfoVos.splice(index, 1);
}

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getPropertyDetailApi(id);
    if (res.code == 200) {
      requestForm.value = {
        ...res.data,
      };
      // 存在为null无法push场景
      if (!requestForm.value.suppFileInfoVos) {
        requestForm.value.suppFileInfoVos = [];
      }
    }

    const response = await getEndFlag(id);
    endFlag.value = response;
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 申请类型0：软件著作权；1：发明专利；2：实用新型专利；3：论文
  await getDictsApi("erp_application_type").then((res) => {
    if (res.code === 200) {
      applicationList.value = res.data;
    }
  });
  await getUserListApi({}).then((res) => {
    if (res.length > 0) {
      userList.value = res;
    }
  });
}
onMounted(() => {
  getDicts();
  if (props.pageType === "add") {
    requestForm.value.userId = userStore.id;
    requestForm.value.deptName = userStore.deptName;
  }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;

  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }

  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }

  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }

  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
}

.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}

.auto-item {
  width: 125px;
  text-align: left;
  white-space: nowrap;
  /* 禁止换行 */
  overflow: hidden;
  /* 隐藏超出部分 */
  text-overflow: ellipsis;
  /* 使用省略号表示超出部分 */
}

.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px;
  /* 设置最大高度 */
  overflow-y: auto;
  /* 超出高度时显示滚动条 */
}
:deep(.el-form-item--default) {
  margin-bottom: 22px;
}
:deep(.el-form-item--default .el-form-item__error) {
  padding-top: 5px;
}
:deep(.el-form-item--default) {
  margin-bottom: 22px;
}
:deep(.el-form-item--default .el-form-item__error) {
  padding-top: 5px;
}
</style>
